package me.luger.core.aspect.log;

import me.luger.core.commom.util.LogUtil;
import me.luger.core.mvc.WebService;
import me.luger.core.mvc.log.access.AccessLogEntity;
import me.luger.core.mvc.log.service.ServiceLogEntity;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/8/21 0021.
 */
@Aspect
@Component
public class ServiceLogAspect {

    ThreadLocal<Long> startTime = new ThreadLocal<Long>();

    @Pointcut("execution(* me.luger.project..*.*service..*(..))")
    public void serviceLog(){}

    @Around("serviceLog()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        Object o = null;
        try{
            ServiceLogEntity serviceLogEntity = new ServiceLogEntity();
            serviceLogEntity.setBeginTime(System.nanoTime());
            AccessLogEntity accessLogEntity = WebService.getAccessLogEntity();
            serviceLogEntity.setLogId(LogUtil.getLogId());

            o = pjp.proceed();

            serviceLogEntity.setEndTime(System.nanoTime());

            List<ServiceLogEntity> serviceLogEntityList = accessLogEntity.getServiceLogEntityList();
            if(null == serviceLogEntityList){
                serviceLogEntityList = new ArrayList<ServiceLogEntity>();
            }
            serviceLogEntity.setExpend(serviceLogEntity.getEndTime() - serviceLogEntity.getBeginTime());
            serviceLogEntityList.add(serviceLogEntity);
            accessLogEntity.setServiceLogEntityList(serviceLogEntityList);
            WebService.setAccessLogEntity(accessLogEntity);
        }catch (Exception e){
            o = pjp.proceed();
        }

        return o;
    }

    //    @Before("serviceLog()")
//    public void doBefore(JoinPoint joinPoint) throws Throwable {
//        startTime.set(System.currentTimeMillis());
//
//        // 省略日志记录内容
//    }
//
//    @AfterReturning(returning = "ret", pointcut = "serviceLog()")
//    public void doAfterReturning(Object ret) throws Throwable {
//        // 处理完请求，返回内容
//        LogUtil.debugLog("RESPONSE : " + ret);
//        LogUtil.debugLog("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
//    }

}
